<template>
  <view class="videoDetail" :class="{'tabbarHeiht': shareRouteData.shareType}">
    <view
       v-if="!videoList.length && routeData.currentPage > 1"
      class="goBack_box"
      :style="'top:'+globalData.menuButtonObject.top+'px;'"
      @click.stop="goBackFn">
      <image v-if="routerlength <= 1" src="@/static/image/goHome_con.png" mode="widthFix" style="width:100%;height:100%;" />
      <image v-else src="@/static/image/goBack_con.png" mode="widthFix" style="width:100%;height:100%;" />
    </view>

    <swiper
      class="video_swiper"
      vertical
      :skip-hidden-item-layout="true"
      @change="onSwiperChange"
    >
      <swiper-item v-for="(item, index) of videoList" :key="index">
        <scroll-view scroll-y style="height:100%;" @scroll="_scrollFn">
          <view class="flex-col" style="min-height: 100%;">
            
            <!-- 吸顶盒子 -->
            <view :style="'height:'+globalData.navHeight+'px;'"></view>
            <view class="headBoxFixed opc1">
              <view :style="'height:'+globalData.navTop+'px;'"></view>
              <view class="headGroupBox">
                <view class="navBack" @click.stop="goBackFn"><image src="@/static/image/navBack_icon.png" style="width:100%;height:100%;border-radius: 50%;display: block;" /></view>
                
                <view class="headImgBox" @click="goHomePage">
                  <image :src="item.communityLogo" mode="aspectFill" style="width:100%;height:100%;border-radius: 50%;" />
                </view>
                <view class="fz-16 fw5 ov1" style="max-width:250rpx;" @click="goHomePage">{{item.communityName}}</view>
                <view class="guanzhuBtn" @click="attention" v-if="item.isMyself===0&&item.followStatus === 0">+关注</view>
              </view>
            </view>

            <view class="imageSwiper">
              <swiper
                class="swiper"
                circular
                :current="imageActiveIndex"
                @change="changeImage"
                :style="'height:750rpx;'"
              >
                <swiper-item v-for="(image, idx) in item.dynamicMediaVOList" :key="idx">
                  <view
                    class="u-flex u-row-center"
                    style="wiodth: 100%; height: 100%"
                  >
                    <image
                      :src="image.thumbnail" 
                      style="width: 100%; height: 100%"
                      mode="aspectFill"
                    />
                  </view>
                </swiper-item>
              </swiper>
              <!-- 指示点 -->
              <view class="indicator"
                >{{ imageActiveIndex + 1 }}/{{ item.dynamicMediaVOList.length }}</view
              >
            </view>

            <view class="px32 u-p-t-32 u-p-b-32 bgf">
              <text class="linh-28 fw6">{{item.title}}</text>
            </view>
            <view class="px32 u-p-b-32 bgf" v-show="item.content">
              <text class="linh-28">{{item.content}}</text>
            </view>
            
            <view style="flex:1;"></view>
            <BottomMsg
              :ref="'bottomMsg'+item.dynamicId"
              :item="item"
              :isImagePgae="true"
              :showTabbar="shareRouteData.shareType"
              :newShareShow="shareShow"
              @closeNewShareShow="shareShow = false"
              @open="openBottom"
              @attention="attention"
              @clickLike="clickLike"
              @clickBestead="clickBestead"
              @openMore="moreShow = true"
              @openShare="openShare"
              @goHomePage="goHomePage"
              @toggleTitleShow="(val)=> isFilter = val"
            />
            <view class="tc viceColor u-p-b-24">
              <view><icon class="iconfont icon-arrow_up" :style="((index+1) === videoList.length && routeData.finish) ? 'opacity: 0'  :'opacity: 1'" /></view>
              <view>{{((index+1) === videoList.length && routeData.finish) ? '没有更多了' : '上拉查看下一条'}}</view>
            </view>
          </view>
        </scroll-view>
      </swiper-item>
    </swiper>

    <view class="shareIcon tc" :style="'left:'+moveX+'px;top:'+moveY+'px'" @touchmove.prevent="_drag_hmove" @click="clickMore" v-if="videoList.length">
      <image src="https://qqposs.oss-cn-shenzhen.aliyuncs.com/mpAppImg/icon/share8_icon.png" style="width:100%;height:100%;display:block;" v-if="videoList[swiperIndex].isMyself === 1" />
      <image src="https://qqposs.oss-cn-shenzhen.aliyuncs.com/mpAppImg/icon/share10_icon.png" style="width:100%;height:100%;display:block;" v-if="videoList[swiperIndex].isMyself !== 1" />
    </view>
    <!-- 商品列表弹窗 -->
    <GoodsMsgList
    :show="bottomShow"
    :goodsList="goodsList"
    :goodsCurrent="goodsCurrent"
    :item="videoList[swiperIndex]"
     @close="bottomShow = false" />

    <!-- 更多操作弹窗 -->
    <MorePopup
    :show="moreShow"
    :item="videoList[swiperIndex]"
    :routeData="routeData"
    @close="moreShow = false"
    @openShare="openShare"
    @clickBestead="clickBestead"
    @switchHide="switchHide"
    @removeDynamic="removeDynamic"
    @openUpEndTime="_updateEndTime"
    @isTop="isTop" />

    <!-- 一键帮卖弹窗 -->
    <u-popup v-model="oneSales" mode="bottom" border-radius="14">
      <view class="onePopup safe-bottom">
        <view class="headTitle tc fz-16 fw5">选择帮卖发布方式</view>
        <view class="px32 u-p-t-25 u-p-b-25" @click.stop="configBestead">
          <view class="fz-16">一键帮卖<text class="themeFontColor">（推荐）</text></view>
          <view class="viceColor u-p-t-8">直接复用内容一键帮卖</view>
        </view>
        <view style="height:16rpx;background: #F7F8FA;"></view>
        <view class="tc fz-16 linh-50" style="color:#646566;" @click="oneSales = false">取消</view>
      </view>
    </u-popup>
    <!-- 发布动态开团成功弹窗 -->
    <PublishPopup v-if="isPublishPopup" :sharePublishData="sharePublishData"  @closeSharePublishFn="(flag)=>isPublishPopup=flag" />

    <!-- 视频缺省页 -->
    <view class="default" v-if="!videoList.length && routeData.currentPage > 1">
      没有内容了，快去关注更多达人
    </view>
    <!-- 底部tabbar -->
    <Tabbar v-if="shareRouteData.shareType" />
    <!-- 申请帮卖关系 -->
    <ApplyForHelpSelling
      v-if="isHelpSellingShow"
      :show="isHelpSellingShow"
      :othersInfoData='othersInfoData'
      :routeData="routeData"
      :getRelationType="getRelationType"
      @cancelFn="cancelApplyForFn"
    />
    <!-- 分享好友模板弹窗 -->
    <SharePublicPage
      v-if="isSharePublicPage"
      :shareVideoData="shareVideoData"
      @cancelShareFn="cancelShareFn"
      @posterFn="posterFn"
    />
    <!-- 保存相册海报分享 -->
    <SharePoster
      v-if="posterShareShow"
      :shareVideoData="shareVideoData"
      @cancelSharePosterFn="cancelSharePosterFn"
    />
    <!-- 已经帮卖弹窗 -->
    <SoldForHelpSell v-if="isSoldForHelpSellShow" @closeSoldForFn="closeSoldForFn" @refreshOwnFn="refreshOwnFn" :soldForHelpSellId="soldForHelpSellId" />
  </view>
</template>
<script>
import Tabbar from "@/components/tabbar/index.vue";
import BottomMsg from "./bottomMsg.vue";
import GoodsMsgList from "./goodsMsgList.vue";
import MorePopup from "./morePopup.vue";
import dynamic from "@/api/dynamic.js";
import mini from "@/api/mini.js";
import supply from "@/api/supply.js";
import helpSellGroups from "@/api/helpSellGroups.js";
import mixin from "./videoDetail.js";
import Util from "@/api/util.js";
import PublishPopup from "@/components/publishPopup/index.vue";
import ApplyForHelpSelling from "../components/applyForHelpSelling.vue";
import SoldForHelpSell from '@/components/soldForHelpSell/index.vue'

// 分享好友模板
import SharePublicPage from "@/components/shareModal/sharePublicPage.vue"
// 分享海报
import SharePoster from "@/components/shareModal/sharePoster.vue"


export default {
  name: 'videoDetail',
  mixins: [mixin],
  components: {Tabbar, BottomMsg, GoodsMsgList, MorePopup, PublishPopup, SharePublicPage, SharePoster, ApplyForHelpSelling, SoldForHelpSell},
  computed: {
    globalData() {
      return this.$store.state.globalData;
    },
    // 是否通过分享进来，展示tabbar
    shareRouteData () {
      return this.$store.state.shareRouteData
    },
    // 分享进来邀请帮卖查询用户信息
    othersInfoData () {
      return this.$store.state.othersInfoData
    },
    // store中的关注后对象
    followTypeObj() {
      return this.$store.state.followTypeObj
    }
  },
  watch:{
    isLogin(nval,oval){
      if(nval !== oval && nval){ // 登录状态更新,从未登录到登录
        this.getData()
      }
    },
    followTypeObj(nVal) {
      if (nVal) {
        for (let i = 0, length = this.videoList.length; i < length; i++) {
          const item = this.videoList[i]
          if (item.accountId === nVal.accountId) {
            item.followStatus = nVal.followStatus
            // 此处不能清空--因为有两处需要用到--清空在另外一处监听不到
            // this.$store.commit('FOLLOW_TYPE', null)
          }
        }
      }
    }
  },
  data() {
    return {
      routeData: {}, // 请求参数

      videoList: [],
      swiperIndex: 0,

      imageActiveIndex: 0, // 图片swiper当前下标

      bottomShow: false, // 弹窗状态,
      goodsList: [], // 商品列表
      goodsCurrent: 0,// 当前商品下标

      moreShow: false, // 操作弹窗
      oneSales: false, // 一键发布弹窗
      isPublishPopup: false, // 发布开团成功弹窗
      sharePublishData: {}, // 发布成功弹窗数据
      posterShareShow: false, // 海报相册保存弹窗
      posterShareData: {}, // 分享海报数据
      isHelpSellingShow: false, // 申请帮卖弹窗
      getRelationType: 0, // 帮卖关系
      drawWhiteShareCardData: {}, // 白色海报分享数据
      shareCanvasData: {}, // 海报分享绘图数据
      shareVideoData: {}, // 需要分享的视频对象
      isSharePublicPage: false, // 分享模板
      configBesteadDisable: false, //一键帮卖防止重复点击
      isSoldForHelpSellShow: false, // 帮卖过了不可帮卖
      soldForHelpSellId: '', // 已经帮卖返回自己帮卖团的id

      isFilter: false, // 是否高斯模糊

      moveX: 0,
      moveY: 0,
      shareShow: false
    };
  },
  async onLoad(option) {
    wx.hideShareMenu({
      menus: ["shareAppMessage"]
    })
    
    this.moveX = this.globalData.windowWidth - 60
    this.moveY = this.globalData.windowHeight - 220

    await this.isLoSignInFn(option) // 分享参数处理
    this.routeData = Object.assign({currentPage: 1, pageSize: 5, finish: false}, this.$store.state.shareRouteData)
    this.getData()

    // 获取红点规则
    if(this.isLogin){
      mini.getMyPageInfo().then(res=>{
        this.$store.commit('SET_MY_PAGEINFO',res.data)
      })
    }
  },
  onShow(){
    let updateData = this.$store.state.publicUpdateData
    if (updateData) { // 是否需要更新数据
      if (updateData.isFollow && this.videoList[updateData.index]) { // 处理页面去个人主页关注变动更新
        this.videoList[updateData.index].followStatus = updateData.isFollow
        this.$forceUpdate()
      }
      this.$store.commit('PUBLIC_UPDATE_DATA', null)
    }
  },
  onShareAppMessage(res) {
    const item = this.videoList[this.swiperIndex]
    const pageSharingData = this.$store.state.pageSharingData
    let title = ''
    let share_image = ''
    let path = `/pagesB/dynamic/graphicsDetail?dynamicId=${item.dynamicId}&shareType=true&type=2&idCode=${this.$store.state.userInfo.idCode}`
    if (res.from === 'button') {
      // 按钮分享
      if (res.target.id=="publishId") { // 发布成功分享参数
        title = this.sharePublishData.title
        share_image = this.sharePublishData.url
      }
      if (res.target.id=='sharewx') { // 公用分享
        if (pageSharingData.isShareType==2) {
          path = `/pagesB/dynamic/graphicsDetail?dynamicId=${item.dynamicId}&shareType=true&&type=2&applyForHelp=true&idCode=${this.$store.state.userInfo.idCode}`
        }
        title = pageSharingData.title
        share_image = pageSharingData.url
      }
    }
    if (res.from === 'menu') {
      // 菜单分享
      // console.log(res.target)
    }

    // 分享参数打印
    console.log(JSON.parse(JSON.stringify({
      title: title,
      imageUrl: share_image,
      path: path
    })))

    return {
      title: title,
      imageUrl: share_image,
      path: path,
      success (res) {
      },
    }
  },
  //方法
  methods: {
    async getData(type){
      await this.getList() // 获取列表

      this.videoList.length && dynamic.addBrowseLog({dynamicId: this.videoList[this.swiperIndex].dynamicId}) // 统计接口

      // 判断进入第一个动态是否为传入的动态 start
      if(this.videoList.length && this.routeData.dynamicId && this.videoList[0].dynamicId !== this.routeData.dynamicId){
        uni.showToast({
          title: type === 'delete' ? '已为你切换下一个内容' : '内容已经飞走了，已为你切换下一个内容',
          icon: 'none'
        })
      }
      if(type === 'delete'){
        return
      }
      // 判断进入第一个动态是否为传入的动态 end

      // 开团发布成功
      if (this.routeData.isReleasePopup && this.routeData.isReleasePopup>0 && this.videoList.length) this.releaseSuccessFn()
      // 邀请帮卖
      if ((this.routeData.dynamicId==this.videoList[this.swiperIndex].dynamicId)&&this.routeData.applyForHelp) this.getOthersInfoFn(this.videoList[this.swiperIndex].accountId)
    },
    // 获取动态列表
    async getList(){
      console.log(this.routeData,'请求参数');
      if(this.routeData.finish) return // 加载完毕，无更多数据
      let list = ""

      if(this.routeData.headAccountId){// 我的-分销管理-帮卖社群-帮卖的团
        const { data } = await helpSellGroups.getHelpSellDynamic(this.routeData)
        list = data.records
      }else if(this.routeData.groupAccountId){// 我的-分销管理-供货社群-可帮卖的团
        const { data } = await supply.getList(this.routeData)
        list = data.records
      }else if(this.routeData.type == 3 || this.routeData.accountId){// 为社群主页进入
        const { data } = await dynamic.getDynamicList(this.routeData)
        list = data.records
      }else if(this.routeData.type == 2 || this.routeData.shareType){//  为分享进入
        if(this.routeData.shareType){this.routeData.type = 2}
        const { data } = await dynamic.getDynamicList(this.routeData)
        list = data.records
      }else{// 调取首页视频流接口
        const { data } = await mini.getHomeDynamics(this.routeData)
        list = data.records
      }
      // 兼容跳转视频播放
      if(list.length && list[0].mediaType !== 1){
        const { routes } = this.getRoute()
        let fullPath = routes[routes.length - 1].$page.fullPath
        const url = fullPath.replace(/graphicsDetail/g, "videoDetail")
        this.redirectTo({url})
      }
      this.videoList = [...this.videoList,...list]
      if(this.routeData.pageSize === 1){ // 只加载一个动态
        this.routeData.finish = true
        return
      }
      this.routeData.finish = ((this.routeData.currentPage * this.routeData.pageSize) !== this.videoList.length)
      this.routeData.currentPage++ // 再次调取，直接加载下一页
    },
    // 视频列表切换
    onSwiperChange(e) {
      this.imageActiveIndex = 0
      this.swiperIndex = e.detail.current; // 当前播放下标
      this.videoList.length && dynamic.addBrowseLog({dynamicId: this.videoList[this.swiperIndex].dynamicId}) // 统计接口
      if (this.swiperIndex === this.videoList.length - 2 && !this.routeData.finish) {
        // 滑动到倒数第二个视频时-以及数据未加载完毕
        console.log("加载更多");
        this.getList()
      }
    },
    // 图片轮播切换
    changeImage(e) {
      this.imageActiveIndex = e.detail.current;
    },
    _drag_hmove(event) {
      let tag = event.touches;
      // if (tag[0].clientX < 0) {
      //   tag[0].clientX = 0
      // }
      // if (tag[0].clientX > this.globalData.windowWidth) {
      //   tag[0].clientX = this.globalData.windowWidth - 40
      // }
      // this.moveX = tag[0].clientX

      if (tag[0].clientY < this.globalData.navHeight) {
        tag[0].clientY = this.globalData.navHeight
      }
      if (tag[0].clientY > (this.globalData.windowHeight - 220)) {
        tag[0].clientY = (this.globalData.windowHeight - 220)
      }
      this.moveY = tag[0].clientY
    },
    // 点击更多操作
    clickMore(){
      if(!this.isLogin){
        this.navigateTo({ url: '/pagesB/login/index'})
        return
      }
      if(this.videoList[this.swiperIndex].isMyself !== 1){
        if(this.videoList[this.swiperIndex].helpSellStatus === 1){ // 可帮卖
          this.shareShow = true
        }else{
          this.openShare(1) // 直接分享
        }
      }else{
        this.moreShow = true // 打开操作面板
      }
    }
  },
};
</script>
<style lang="scss">
// 不存在tabbar
.videoDetail {
  width: 100%;
  height: 100vh;
  height: calc(100vh - constant(safe-area-inset-bottom));
  height: calc(100vh - env(safe-area-inset-bottom));
  overflow: hidden;
  position: relative;
  background: #F7F8FA;
  .filter24{
    filter: blur(24px);
  } 
  .goBack_box {
    position: fixed;
    z-index: 998;
    width: 60rpx;
    height: 60rpx;
    left: 32rpx;
    top: 48px;
    transition: opacity .5s;
  }
  .goBack_box.opc0{
    opacity: 0;
  }

  .shareIcon{
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    position: fixed;
    z-index: 997;
  }

  .video_swiper {
    width: 100%;
    height: 100%;
  }

  .headBox{
    width:100%;
    height:376rpx;
    // border-radius: 0 0 32rpx 32rpx;
    overflow: hidden;
    position: relative;
    .headGroupMsg{
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 288rpx;
      background: linear-gradient(180deg, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.4) 100%);
      .headGroupBox{
        position: absolute;
        bottom: 32rpx;
        left: 0;
        width: 100%;
        padding: 0 32rpx;
        color: #FFF;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .headImgBox{
          width: 128rpx;
          height: 128rpx;
          border-radius: 50%;
          border: 1px dashed #FFFFFF;
          background-color: #FFFFFF;
          margin-right: 24rpx;
        }
        .guanzhuBtn{
          background: #E44435;
          border-radius: 8rpx;
          width: 128rpx;
          height: 48rpx;
          line-height: 48rpx;
          text-align: center;
          margin-left: 80rpx;
        }
      }
    }
  }

  .headBoxFixed{
    position: fixed;
    z-index: 999;
    top: 0;
    left: 0;
    width: 100%;
    background-color: #FFF;
    opacity: 0;
    transition: opacity .5s;
    .headGroupBox{
      display: flex;
      align-items: center;
      padding-bottom: 8rpx;
      .navBack{
        width: 64rpx;
        height: 64rpx;
        padding: 12rpx;
        margin-left: 24rpx;
        margin-right: 16rpx;
      }
      .headImgBox{
        width: 64rpx;
        height: 64rpx;
        border-radius: 50%;
        background-color: #FFFFFF;
        margin-right: 6rpx;
      }
      .guanzhuBtn{
        height: 48rpx;
        line-height: 48rpx;
        border-radius: 32rpx;
        padding: 0 16rpx;
        background-color: #E44435;
        color: #FFFFFF;
        margin-left: 6rpx;
        font-size: 24rpx;
      }
    }
  }
  .headBoxFixed.opc1{
    opacity: 1;
  }

  .imageSwiper {
    position: relative;
    background-color: #FFFFFF;
    // border-radius: 16rpx;
    overflow: hidden;
    // box-shadow: 0 4rpx 24rpx rgba(150, 151, 153, 0.16);
    .indicator {
      background: rgba(0, 0, 0, 0.4);
      color: #fff;
      font-size: 24rpx;
      border-radius: 32rpx;
      padding: 8rpx 20rpx;
      position: absolute;
      bottom: 24rpx;
      right: 32rpx;
    }
  }

  .bgf{
    background-color: #FFF;
  }


  
  .onePopup{
    .headTitle {
      line-height: 96rpx;
      box-shadow: inset 0px -1px 0px #eeeeee;
    }
  }
  .default{
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: #323233;
    color: #F7F8FA;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

// 存在tabbar
.videoDetail.tabbarHeiht{
  height: calc(100vh - 100rpx);
  height: calc(100vh - 100rpx - constant(safe-area-inset-bottom));
  height: calc(100vh - 100rpx - env(safe-area-inset-bottom));
}

</style>